const cloud = require('wx-server-sdk');
const moment = require('moment');
const _ = require('lodash');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database({ env: cloud.DYNAMIC_CURRENT_ENV });

/**
 * 获取当天的打卡记录数据
 * @param {*} event 
 * @param {*} context 
 */
exports.main = async (event, context) => {
  // 获取基础数据
  const wxContext = cloud.getWXContext();
  const where_params = {
    openid: wxContext.OPENID,
    group_name: '打卡点',
    day_time: moment().format('YYYY-MM-DD'),
  };
  try {
    const record_res = await db.collection('daka_records').where(where_params).orderBy('createdAt', 'asc').limit(4).get();
    const list = record_res.data || [];
    const duration = _.sumBy(list, 'duration')/(3600 * 1000) || 0;
    const data = {
      code: 0,
      msg: 'OK',
      openid: wxContext.OPENID,
      next_type: 'SIGN_IN',
      today: moment(where_params.day_time).format('YYYY年MM月DD日'),
      duration: duration.toFixed(1),
      list,
    };
    const last_index = list.length - 1;
    if (last_index >= 0) {
      const type = list[last_index].type;
      data.next_type = type === 'SIGN_OUT' ? 'SIGN_IN' : 'SIGN_OUT'
    }
    return data;
  } catch (error) {
    throw { code: -1, msg: error.message };
  }
};